'use strict';
const Log = require('../model/log');
const User = require('../model/user');
const sequelize = require('../util/sequelize');
const LoginService = require('qcloud-weapp-server-sdk').LoginService;

module.exports = (req, res) => {
    LoginService.create(req, res).login(function(err, result) {
        if (result && result.userInfo) {
            var openId = result.userInfo.openId;
            // 检查业务数据库是否存在该openId的用户
            User.findOne({
                where: {
                    openId: openId
                }
            }).then(function(user) {
                if (user && user != null) {
                    // 存在 不处理
                    console.log("存在用户");
                } else {
                    var number = 10000;
                    // 不存在 新增用户
                    console.log("不存在用户");
                    // 查询当前最大的 id
                    User.max('id').then(function(max) {
                        if (!isNaN(max)) {
                            number += max;
                        }
                        // 创建新的业务用户
                        User.create({
                            number: number,
                            openId: openId,
                            nickName: result.userInfo.nickName,
                            gender: result.userInfo.gender,
                            language: result.userInfo.language,
                            city: result.userInfo.city,
                            province: result.userInfo.province,
                            country: result.userInfo.country,
                            avatarUrl: result.userInfo.avatarUrl,
                        });
                        // console.log("max :" + max)
                    }).catch(function(err) {
                        console.log(err);
                    });
                }
            })

        }
        var jsonStr = JSON.stringify(result);

        console.log("login success! result:" + jsonStr);
    });
};